package com.tgy.algorithm.base;



public class _删除链表中指定的元素 {

    public static Node generateLinked(int[] nums) {

        if (nums == null || nums.length == 0) {
            return null;
        }

        Node head = null;
        Node current = null;

        for (int i = 0; i < nums.length; i++) {
            Node node = new Node(nums[i],null);
            if(head == null) {
                head = node;
                current = node;
            }else {
                current.next = node;
                current = node;
            }
        }

        return head;
    }

    public static void printLinked(Node head) {
        while (head != null) {
            System.out.print(head.num + " ");
            head = head.next;
        }
        System.out.println();
    }

    public static Node removeDuplicates(Node head,int num) {

        Node newNode = null;
        Node current = head;
        // 先找头
        while (current != null) {
            if (current.num != num) {
                newNode = current;
                break;
            }
            current = current.next;
        }

        Node pre = null;
        current = newNode;
        boolean flag = false;
        // 1 2 3     3
        while (current != null) {
            if (current.num == num) {
                flag = true;
            }else {
                // 这里为pre赋值，只有有相等的时候，才进行赋值
                if (flag) {
                    pre.next = current;
                    flag = false;
                }
                pre = current;
            }
            current = current.next;
        }

        // 移除最后的2
        if (flag) {
            pre.next = null;
        }

        return newNode;
    }

    public static Node removeDuplicates2(Node head,int num) {

        Node newNode = null;

        // 删除头部元素
        while (head != null) {
            if (head.num != num) {
//                head = head.next;
                newNode = head;
                break;
            }
            head = head.next;
        }

        Node pre = newNode;

        while (head != null) {
            // 每一步都更新pre.next
            if(head.num == num) {
                pre.next = head.next;
            }else {
                pre = head;
            }
            head = head.next;
        }

        return newNode;
    }

    public static void main(String[] args) {
        Node node = generateLinked(new int[]{2,2,3,4,2,2,6,2,8,2,1});
        printLinked(node);
//        Node removeNode = removeDuplicates(node,2);
        Node removeNode = removeDuplicates2(node,2);
        printLinked(removeNode);
    }
}
